<template>
  <div
    v-loading="loading"
    class="attachment-excel flex-row"
    element-loading-text="正在上传..."
    element-loading-background="rgba(0,0,0,0.5)">
    <ul class="flex-item file-list" style="overflow: hidden">
      <template v-if="files && files.length">
        <li v-for="file in files" :key="file.id" class="file-list-item flex-row" style="overflow: hidden">
          <p class="file-list-item-name flex-item ellipsis-1" :title="file.fileName" @click="preview(file)">
            <i class="el-icon-document"></i> {{ file.fileName }}
          </p>
          <ElButton
            class="flex-not-shrink"
            title="点击下载"
            type="text"
            icon="el-icon-download"
            style="color: #606266"
            @click="download(file.id, { fileName: file.fileName })" />
          <ElButton
            v-if="!disabled"
            class="flex-not-shrink"
            title="删除"
            type="text"
            icon="el-icon-delete"
            style="color: #606266"
            @click="removeFile(file)" />
        </li>
      </template>
      <li v-else style="text-align: center">暂无文件！</li>
    </ul>
    <ElUpload
      v-if="!disabled && files.length < limitFileSize"
      :accept="
        accept
          .split(',')
          .map(item => `.${item}`)
          .join(',')
      "
      :action="getUploadUrl()"
      :headers="getHeader()"
      auto-upload
      :multiple="multiple"
      :data="{ unid, templateFileKey }"
      :before-upload="beforeUploadFile"
      :on-success="onFileUploadSuccess"
      :on-error="onError"
      :on-remove="removeFile"
      class="upload-in-right"
      :show-file-list="false"
      drag>
      <div class="el-upload__text">请将文件拖到此处，或<em>点击此处</em>。</div>
    </ElUpload>
    <ElementDialog width="450px" center title="系统提示" :visible.sync="show" @closed="errorFiles = []">
      <ul style="min-height: 200px; max-height: 70vh; overflow: auto">
        <li v-for="item in errorFiles" :key="item.file.id" style="margin-bottom: 10px; padding: 0 10px">
          <p style="font-weight: bold; line-height: 1.8">
            {{ item.file.name }}
            <span style="margin-left: 10px; color: #f56c6c; font-weight: normal"
              ><i class="el-icon-warning"></i>上传失败</span
            >
          </p>
          <p style="color: #f56c6c; line-height: 1.8">{{ item.data.message }}</p>
        </li>
      </ul>
    </ElementDialog>
  </div>
</template>

<script>
  import { getFileSuffix } from '@web-utils/core'
  import { getUploadUrl, getHeader, download, findAllByParentUnid, remove } from '@/api/attachment/attachment'
  import { openFile } from '@/api/file-view'

  export default {
    name: 'AttachmentExcel',
    props: {
      unid: String,
      templateFileKey: String,
      limitFileSize: Number,
      fileTag: String,
      dataTplId: String,
      disabled: {
        type: Boolean,
        default: false
      },
      multiple: {
        type: Boolean,
        default: false
      },
      accept: {
        type: String,
        default: 'xls,xlsx'
      }
    },
    data() {
      return {
        errorFiles: [],
        successFiles: [],
        accessedFiles: [],
        files: [],
        show: false,
        loading: false
      }
    },
    computed: {
      first() {
        return this.files?.[0]
      }
    },
    watch: {
      unid: {
        immediate: true,
        async handler() {
          await this.fetchAttachments()
        }
      }
    },
    methods: {
      getUploadUrl,
      getHeader,
      download,
      beforeUploadFile(file) {
        this.loading = true
        const ext = this.accept.split(',').includes(getFileSuffix(file.name)?.toLowerCase())
        if (!ext && this.accept !== '*') {
          this.$message.warning(`只能上传后缀为${this.accept}的文件`)
          this.loading = false
          return false
        }
        this.accessedFiles.push(file)
      },
      onFileUploadSuccess(response, file) {
        if (response.code === 0) {
          this.successFiles.push(file)
          this.fetchAttachments()
          this.$emit('on-success', { ...response.data, dataTplId: this.dataTplId, fileTag: this.fileTag })
        } else {
          this.errorFiles.push({ file, data: response })
        }
        this.showErrorTips()
      },
      onError(res, file) {
        this.errorFiles.push({ file, data: res.message })
        this.loading = false
        this.showErrorTips()
      },
      showErrorTips() {
        if (this.successFiles.length + this.errorFiles.length === this.accessedFiles.length) {
          this.loading = false
          this.successFiles = []
          this.accessedFiles = []
          if (this.errorFiles.length) {
            this.show = true
          }
        }
      },
      async remove(file) {
        if (file && file.id) {
          await remove(file.id)
          this.$emit('on-remove', file)
          await this.fetchAttachments()
        }
      },
      async removeFirst() {
        await this.remove(this.first)
      },
      async removeFile(file) {
        if (file.id) {
          await this.remove(file)
          this.$message.success('删除成功!')
        }
      },
      async preview(row) {
        await openFile(row, {
          wordType: 'file',
          mode: 'view',
          callback() {
            // addBrowse({
            //   type: 'Excel模板填报类',
            //   name: row.fileName,
            //   srcId: row.id,
            //   attachmentId: row.id,
            //   fileType: row.fileType
            // })
          }
        })
      },
      async fetchAttachments() {
        if (this.unid && this.unid !== '') {
          const res = await findAllByParentUnid(this.unid, this.type)
          if (res.code === 0) {
            const { data } = res
            this.files = data || []
            return
          } else {
            this.$message.error(res.message)
          }
        }
        this.files = []
      }
    }
  }
</script>

<style lang="scss">
  .attachment-excel {
    display: flex;
    min-height: 50px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 4px;

    .file-list {
      max-width: 420px;
      padding: 6px;
      list-style: none;
      border: 1px solid #d9d9d9;
    }

    .file-list-item {
      position: relative;
      align-items: center;
      box-sizing: border-box;
      width: 100%;
      margin-top: 2px;
      color: #606266;
      font-size: 14px;
      line-height: 1.8;
      border-radius: 4px;
      transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);

      .el-icon-close {
        flex-shrink: 0;
        visibility: hidden;
        cursor: pointer;
      }

      &:hover {
        .el-icon-close {
          visibility: visible;
        }
      }
    }

    .file-list-item-name {
      display: block;
      margin-right: 10px;
      padding-left: 4px;
      overflow: hidden;
      color: #606266;
      white-space: nowrap;
      text-overflow: ellipsis;
      transition: color 0.3s;

      @include ellipsis-line;

      &:hover {
        color: #409eff;
        cursor: pointer;
      }
    }

    .upload-in-right {
      position: relative;
      flex-shrink: 0;
      width: 280px;
      min-height: 60px;

      .el-upload {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        width: 100%;
      }

      .el-upload-dragger {
        display: flex;
        align-items: center;
        width: 100%;
        height: 100%;
        background: #fafafa;
        border-style: solid;
        border-radius: 0 4px 4px 0;

        .el-upload__text {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
          text-align: center;
        }
      }
    }
  }
</style>
